/**
 * 风控规则设置
 */
angular.module('inspinia').controller('riskRulesSetCtrl',function($scope, $http, $state, $stateParams, i18nService,$filter) {
	i18nService.setCurrentLang('zh-cn');
    $scope.payMethodTypes = angular.copy($scope.payMethodType);
    $scope.tradeStatusLists=[{text:"成功",value:"SUCCESS"},{text:"失败",value:"FAILED"},{text:"初始化",value:"INIT"},{text:"已提交",value:"SENDORDER"}];
    $scope.ratioTransStatusLists=[{text:"失败",value:"FAILED"},{text:"初始化",value:"INIT"},{text:"已提交",value:"SENDORDER"}];
	$scope.info={};
	$scope.allState = false;
	$scope.allMerType= false;
	$scope.allScope = {};
    $scope.merTypeList=[];
    //$scope.checkStatus1 = false;
    //$scope.checkStatus2 = false;
	$scope.isCiTiaoCard=[{text:"是",value:"是"},{text:"否",value:"否"}];
	$scope.isXinPianCard=[{text:"是",value:"是"},{text:"否",value:"否"}];
//	$scope.nodes=[{text:"交易",value:1},{text:"审件",value:2},{text:"提现",value:3},{text:"实名认证",value:4}];
	
	
	 $scope.selectAll = function(m) {
		 $scope.allState = m.target.checked;
		 for(var i=0;i<$scope.allScope.length;i++){
	          $scope.allScope[i].state=false;
	     }
     };
        $scope.updateSelection = function ($event, id) {
            if ($event.target.checked) {
            	$scope.allState = false;
            }
        };
    $scope.selectMerTypeAll = function(m) {
        $scope.allMerType = m.target.checked;
        for(var i=0;i<$scope.merTypeList.length;i++){
            $scope.merTypeList[i].state=false;
        }
    };
    $scope.updateMerTypeSelection = function ($event, id) {
        if ($event.target.checked) {
            $scope.allMerType = false;
        }
    };

    $scope.getDatailInfo=function(){
        $http.post('riskRulesAction/selectByParam',
            "ids="+angular.toJson($stateParams.id),
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function(data){
                if(!data.bols){
                    $scope.notice(data.msg);
                    return;
                }

                $scope.allScope = data.teaminfos;

                //响应成功
                $scope.merTypeList = [];
                for(var i=0; i<data.merTypeInfos.length; i++){
                    $scope.merTypeList.push({value:data.merTypeInfos[i].sysValue,text:data.merTypeInfos[i].sysName,state:false});
                }

                $scope.info=data.result;
                $scope.values=data.values;
                if($scope.info.rulesNo == 115){
                    var riskStatus = ($scope.values.riskStatus).split(",");
                    $scope.riskStatus1 = riskStatus[0];
                    $scope.riskStatus2 = riskStatus[1];
                    if($scope.riskStatus1==3){
                        $scope.checkStatus1 = true;
                    }
                    if($scope.riskStatus2==2){
                        $scope.checkStatus2 = true;
                    }
                }

                if($scope.info.rulesNo == 134){
                    var hourInTransStatus = ($scope.values.hourInTransStatus).split(",");
                    $scope.hourInTransStatus1 = '';
                    $scope.hourInTransStatus2 = '';
                    $scope.hourInTransStatus3 = '';
                    $scope.hourInTransStatus4 = '';
                    angular.forEach(hourInTransStatus,function(item){
                        $scope.changeHourInTransStatus(item);
                    });

                    var dayTransStatus = ($scope.values.dayTransStatus).split(",");
                    $scope.dayTransStatus1 = '';
                    $scope.dayTransStatus2 = '';
                    $scope.dayTransStatus3 = '';
                    $scope.dayTransStatus4 = '';
                    angular.forEach(dayTransStatus,function(item){
                        $scope.changeDayTransStatus(item);
                    });

                    var transStatus = ($scope.values.transStatus).split(",");
                    $scope.transStatus1 = '';
                    $scope.transStatus2 = '';
                    $scope.transStatus3 = '';
                    $scope.transStatus4 = '';
                    angular.forEach(transStatus,function(item){
                        $scope.changeTransStatus(item);
                    });
                }
                if($scope.info.rulesNo == 135){

                    $scope.values.transStatus=$scope.changeStrToArr($scope.values.transStatus);
                    $scope.values.payMethod=$scope.changeStrToArr($scope.values.payMethod);
                    $scope.values.tranckTransStatus=$scope.changeStrToArr($scope.values.tranckTransStatus);
                    $scope.values.tranckPayMethod=$scope.changeStrToArr($scope.values.tranckPayMethod);
                    $scope.values.ratioTransStatus=$scope.changeStrToArr($scope.values.ratioTransStatus);

                    //多选项回显
                    $scope.initMultiselect("#transStatus-multiple-selected",$scope.tradeStatusLists,$scope.values.transStatus);
                    $scope.initMultiselect("#payMethod-multiple-selected",$scope.payMethodTypes,$scope.values.payMethod);
                    $scope.initMultiselect("#tranckTransStatus-multiple-selected",$scope.tradeStatusLists,$scope.values.tranckTransStatus);
                    $scope.initMultiselect("#tranckPayMethod-multiple-selected",$scope.payMethodTypes,$scope.values.tranckPayMethod);
                    $scope.initMultiselect("#ratioTransStatus-multiple-selected",$scope.ratioTransStatusLists,$scope.values.ratioTransStatus);

                   /* $('#transStatus-multiple-selected').multiselect();
                    $('#payMethod-multiple-selected').multiselect();
                    $('#tranckTransStatus-multiple-selected').multiselect();
                    $('#tranckPayMethod-multiple-selected').multiselect();
                    $('#ratioTransStatus-multiple-selected').multiselect();*/




                }

                //回显范围

                if("0"==$scope.info.rulesTeamIds){
                    $scope.allState = true;
                }else{
                    for(var i=0;i<$scope.allScope.length;i++){
                        if($scope.info.rulesTeamIds!=null && $scope.info.rulesTeamIds!=""){
                            if($scope.info.rulesTeamIds.indexOf($scope.allScope[i].teamId)!=-1){
                                $scope.allScope[i].state=true;
                            }else{
                                $scope.allScope[i].state=false;
                            }
                        }
                    }}

                //回显商户类型

                if("0"==$scope.info.rulesMerchantType){
                    $scope.allMerType = true;
                }else{
                    for(var i=0;i<$scope.merTypeList.length;i++){
                        if($scope.info.rulesMerchantType!=null && $scope.info.rulesMerchantType!=""){
                            if($scope.info.rulesMerchantType.indexOf($scope.merTypeList[i].value)!=-1){
                                $scope.merTypeList[i].state=true;
                            }else{
                                $scope.merTypeList[i].state=false;
                            }
                        }
                    }}
            })
    };

    $scope.initMultiselect=function(selId,list,valueList){
        $(selId).empty();
        var select = $(selId);
        for (var i = 0; i < list.length; i++) {
             //添加选项
            select.append("<option value='" + list[i].value + "'>" + list[i].text + "</option>");
        }
        if (null != valueList && valueList.length > 0) {
            for (var j = 0; j < valueList.length; j++) {
                // 设置选中项
                $(selId+"  option[value='" +valueList[j] + "'] ").attr("selected", true);
            }
        }

        $(selId).multiselect();
    }


    $scope.getDatailInfo();

    //屏蔽规则指令2、3、5
    $scope.rulesInstructionModals=angular.copy($scope.rulesInstructions);
    $scope.rulesInstructionModals.splice(5, 1);//屏蔽规则指令{text:"实名认证",value:5}
    $scope.rulesInstructionModals.splice(2, 2);//屏蔽规则指令{text:"身份证黑名单",value:2}、{text:"银行卡黑名单",value:3}
    $scope.rulesInstructionModals.splice(0, 1);//屏蔽规则指{text:"全部",value:-1}
	
	$scope.rulesInstructionSelcet=1;
    $scope.modifyRulesInstruction=function(rulesNo,rulesInstruction){
        $scope.rulesInstructionSelcet=rulesInstruction;
    	$scope.rulesInstruction=rulesInstruction;
    	$scope.rulesNo=rulesNo;
    	$('#modifyRulesInstructionModal').modal('show');
    }
    
    $scope.modifyRulesInstructionColse=function(){
    	$('#modifyRulesInstructionModal').modal('hide');
    }
    
    $scope.modifyRulesInstructionCommit=function(){
    	var data={"rulesNo":$scope.rulesNo,"rulesInstruction":$scope.rulesInstructionSelcet}
    	$http.post("riskRulesAction/modifyRulesInstruction",angular.toJson(data))
		.success(function(msg){
			if(msg.bols){
				$scope.notice(msg.msg);
                $scope.getDatailInfo();
				$('#modifyRulesInstructionModal').modal('hide');
			}else{
				$scope.notice(msg.msg);
				$('#modifyRulesInstructionModal').modal('hide');
			}
		}).error(function(){
		});
    }
	$scope.commit=function(){
		
		//$scope.submitting = true;
        if($stateParams.id==114) {
            $scope.info.rulesProvincesList = angular.toJson($scope.provinceGridApi.selection.getSelectedRows());
            $scope.info.rulesCityList = angular.toJson($scope.cityGridApi.selection.getSelectedRows());
        }
        if($stateParams.id==115){
            if($scope.riskStatus1 == 0 && $scope.riskStatus2 == 0){
                $scope.notice("商户状态至少选择一个");
                $scope.submitting = false;
                return;
            }
            if($scope.values.accBalanceLimit == "" || $scope.values.accBalanceLimit == null){
                $scope.notice("账户余额不能为空");
                $scope.submitting = false;
                return;
            }
            $scope.values.riskStatus = $scope.riskStatus1+","+$scope.riskStatus2;
        }

        if($stateParams.id==134){
            $scope.values.hourInTransStatus = ($scope.hourInTransStatus1==''?'':$scope.hourInTransStatus1+",")+
                ($scope.hourInTransStatus2==''?'':$scope.hourInTransStatus2+",")+
                ($scope.hourInTransStatus3==''?'':$scope.hourInTransStatus3+",")+
                ($scope.hourInTransStatus4==''?'':$scope.hourInTransStatus4+",");
            if($scope.values.hourInTransStatus!=''){
                $scope.values.hourInTransStatus=$scope.values.hourInTransStatus.substring(0,$scope.values.hourInTransStatus.length-1);
            }else{
                $scope.notice("交易状态至少勾选一个");
                return;
            }
            $scope.values.dayTransStatus = ($scope.dayTransStatus1==''?'':$scope.dayTransStatus1+",")+
                ($scope.dayTransStatus2==''?'':$scope.dayTransStatus2+",")+
                ($scope.dayTransStatus3==''?'':$scope.dayTransStatus3+",")+
                ($scope.dayTransStatus4==''?'':$scope.dayTransStatus4+",");
            if($scope.values.dayTransStatus!=''){
                $scope.values.dayTransStatus=$scope.values.dayTransStatus.substring(0,$scope.values.dayTransStatus.length-1);
            }else{
                $scope.notice("交易状态至少勾选一个");
                return;
            }
            $scope.values.transStatus = ($scope.transStatus1==''?'':$scope.transStatus1+",")+
                ($scope.transStatus2==''?'':$scope.transStatus2+",")+
                ($scope.transStatus3==''?'':$scope.transStatus3+",")+
                ($scope.transStatus4==''?'':$scope.transStatus4+",");
            if($scope.values.transStatus!=''){
                $scope.values.transStatus=$scope.values.transStatus.substring(0,$scope.values.transStatus.length-1);
            }else{
                $scope.notice("交易状态至少勾选一个");
                return;
            }
        }

        if($stateParams.id==135){

            if($scope.values.transStatus.length==0
                ||$scope.values.tranckTransStatus.length==0
                ||$scope.values.ratioTransStatus.length==0
            ){
                $scope.notice("交易状态至少勾选一个");
                return;
            }

            if($scope.values.payMethod.length==0
                ||$scope.values.tranckPayMethod.length==0
            ){
                $scope.notice("交易方式至少勾选一个");
                return;
            }
            if(!isPositiveNum($scope.values.registeredDay)
                ||!isPositiveNum($scope.values.transNum)
                ||!isPositiveNum($scope.values.realAuthDay)
                ||!isPositiveNum($scope.values.tranckCardNum)
            ){
                $scope.notice("请输入正整数");
                return;
            }
            if(!isPercent($scope.values.tranckRatio)
                ||!isPercent($scope.values.ratio)
            ){
                $scope.notice("百分比请控制输入在0~100以内");
                return;
            }


            $scope.values.transStatus=$scope.changeArrToStr($scope.values.transStatus);
            $scope.values.payMethod=$scope.changeArrToStr($scope.values.payMethod);
            $scope.values.tranckTransStatus=$scope.changeArrToStr($scope.values.tranckTransStatus);
            $scope.values.tranckPayMethod=$scope.changeArrToStr($scope.values.tranckPayMethod);
            $scope.values.ratioTransStatus=$scope.changeArrToStr($scope.values.ratioTransStatus);

            //$scope.notice(angular.toJson($scope.values));
           // return;
        }

        if($stateParams.id==136) {
            if(!isPositiveNum($scope.values.registeredTime)
                ||!isPositiveNum($scope.values.numMinute)
                ||!isPositiveNum($scope.values.tradeNum)
                ||!isPositiveNum($scope.values.amountMinute)
            ){
                $scope.notice("请输入正整数");
                return;
            }
            if(!decimalTwo($scope.values.totalAmount)) {
                $scope.notice("请输入最多两位小数的正数");
                return;
            }
        }

        if($scope.allState){
        	$scope.info.rulesTeamIds = "0";
        }else{
            var str = "";
        	for(var i=0;i<$scope.allScope.length;i++){
        		 if($scope.allScope[i].state){
        			 str += "," + $scope.allScope[i].teamId;
        		 }
        	 }
        	 if(str != ""){
                 str = str.substring(1);
                 $scope.info.rulesTeamIds = str;
             }else{
            	 $scope.info.rulesTeamIds = "";
             }
        }
        if($scope.allMerType){
            $scope.info.rulesMerchantType = "0";
        }else{
            var merstr = "";
            for(var i=0;i<$scope.merTypeList.length;i++){
                if($scope.merTypeList[i].state){
                    merstr += "," + $scope.merTypeList[i].value;
                }
            }
            if(merstr != ""){
                merstr = merstr.substring(1);
                $scope.info.rulesMerchantType = merstr;
            }else{
                $scope.info.rulesMerchantType = "";
            }
        }



        $scope.summitInfo=angular.copy($scope.info);
        $scope.summitInfo.rulesEngine=null;
		$http.post('riskRulesAction/updateInfo',
			"info="+angular.toJson($scope.summitInfo)+"&values="+angular.toJson($scope.values),
			 {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
	    .success(function(data){
			if(!data.bols){
				$scope.notice(data.msg);
				$scope.submitting = false;
			}else{
				$scope.notice(data.msg);
				$state.transitionTo('risk.riskRulesMag',null,{reload:true});
				$scope.submitting = false;
			}
			
	    })
	    
	}

	if($stateParams.id==114){
        //获取所有省份
        $scope.getAreaList=function(name,type,callback){
            if(name == null || name=="undefine"){
                return;
            }
            $http.post('areaInfo/getAreaByName.do','name='+name+'&&type='+type,
                {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
            ).success(function(data){
                callback(data);
            }).error(function(){
            });
        }
        $scope.getAreaList(0, "p", function (data) {
            $scope.provinceGrid.data = data;
        });

        //商户省份表格
        $scope.provinceGrid = {
            columnDefs: [
                {field: 'name',displayName: '省份',width: 200},
            ],
            onRegisterApi : function(gridApi) {
                $scope.provinceGridApi = gridApi;
                $scope.provinceGridApi.selection.on.rowSelectionChanged($scope,function(row,event){
                    //行选中事件
                    $scope.findCity();
                });
                $scope.provinceGridApi.selection.on.rowSelectionChangedBatch($scope,function(row,event){
                    //全选事件
                    $scope.findCity();
                });
            },
            isRowSelectable: function(row){ // 选中行
                if($scope.info.provincesList){
                    for(var i=0;i<$scope.info.provincesList.length;i++){
                        if(row.entity.name==$scope.info.provincesList[i]){
                            row.grid.api.selection.selectRow(row.entity);
                            break;
                        }
                    }
                }
            }
        };

        $scope.findCity=function(){
            $http.post("areaInfo/getAreaCityByParentId",angular.toJson({provinceList:$scope.provinceGridApi.selection.getSelectedRows()})).success(function(data){
                $scope.cityGrid.data = data;
            });
        }

        //商户市表格
        $scope.cityGrid = {
            columnDefs: [
                {field: 'name',displayName:'市',width: 200},
            ],
            onRegisterApi : function(gridApi) {
                $scope.cityGridApi = gridApi;
            },
            isRowSelectable: function(row){ // 选中行
                if($scope.info.cityList){
                    for(var i=0;i<$scope.info.cityList.length;i++){
                        if(row.entity.name==$scope.info.cityList[i]){
                            row.grid.api.selection.selectRow(row.entity);
                            break;
                        }
                    }
                }
            }
        };
	}

    $scope.changeArrToStr = function (arrStr) {
        if(arrStr==null||arrStr.length==0){
            return;
        }
        var newStr="";
        for(var i=0;i<arrStr.length;i++){

            newStr=newStr+arrStr[i]+",";
        }
        newStr=newStr.substring(0,newStr.length-1);
        return newStr;
    }

    $scope.changeStrToArr = function (str) {
        if(str==null||str==""){
            return;
        }
        var arrStr=str.split(",");
        return arrStr;
    }

    //验证是否为正整数
    isPositiveNum = function (s) {
        var re = /^[0-9]+$/;
        if(re.test(s)){
            return parseInt(s)>=0;
        }
        return false;
    }

    //百分比0~100
    isPercent = function (s) {
        var re= /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/g;
        if(re.test(s)){
            return s>=0&&s<=100;
        }
        return false;
    }

	decimalTwo = function(s){
	    var re = /^(([1-9]{1}\d*)|(0))(\.\d{1,2})?$/;
	    return re.test(s);
    }


	//改变复选框状态
    $scope.changeStatus = function (i) {
        if(i == 3){
            $scope.riskStatus1 = ($scope.riskStatus1 == 0 ? i : 0);
            $scope.checkStatus1 = ($scope.riskStatus1 == i ? true : false);
        }
        if(i == 2){
            $scope.riskStatus2 = ($scope.riskStatus2 == 0 ? i : 0);
            $scope.checkStatus2 = ($scope.riskStatus2 == i ? true : false);
        }
    }

    //改变复选框状态134
    $scope.changeHourInTransStatus = function (i) {
        if(i == 'SUCCESS'){
            $scope.hourInTransStatus1 = ($scope.hourInTransStatus1 == i ? '' : i);
            $scope.checkHourInTransStatus1 = ($scope.hourInTransStatus1 == i ? true : false);
        }
        if(i == 'FAILED'){
            $scope.hourInTransStatus2 = ($scope.hourInTransStatus2 == i ? '' : i);
            $scope.checkHourInTransStatus2 = ($scope.hourInTransStatus2 == i ? true : false);
        }
        if(i == 'INIT'){
            $scope.hourInTransStatus3 = ($scope.hourInTransStatus3 == i ? '' : i);
            $scope.checkHourInTransStatus3 = ($scope.hourInTransStatus3 == i ? true : false);
        }
        if(i == 'SENDORDER'){
            $scope.hourInTransStatus4 = ($scope.hourInTransStatus4 == i ? '' : i);
            $scope.checkHourInTransStatus4 = ($scope.hourInTransStatus4 == i ? true : false);
        }
    }
    $scope.changeDayTransStatus = function (i) {
        if(i == 'SUCCESS'){
            $scope.dayTransStatus1 = ($scope.dayTransStatus1 == i ? '' : i);
            $scope.checkDayTransStatus1 = ($scope.dayTransStatus1 == i ? true : false);
        }
        if(i == 'FAILED'){
            $scope.dayTransStatus2 = ($scope.dayTransStatus2 == i ? '' : i);
            $scope.checkDayTransStatus2 = ($scope.dayTransStatus2 == i ? true : false);
        }
        if(i == 'INIT'){
            $scope.dayTransStatus3 = ($scope.dayTransStatus3 == i ? '' : i);
            $scope.checkDayTransStatus3 = ($scope.dayTransStatus3 == i ? true : false);
        }
        if(i == 'SENDORDER'){
            $scope.dayTransStatus4 = ($scope.dayTransStatus4 == i ? '' : i);
            $scope.checkDayTransStatus4 = ($scope.dayTransStatus4 == i ? true : false);
        }
    }
    $scope.changeTransStatus = function (i) {
        if(i == 'SUCCESS'){
            $scope.transStatus1 = ($scope.transStatus1 == i ? '' : i);
            $scope.checkTransStatus1 = ($scope.transStatus1 == i ? true : false);
        }
        if(i == 'FAILED'){
            $scope.transStatus2 = ($scope.transStatus2 == i ? '' : i);
            $scope.checkTransStatus2 = ($scope.transStatus2 == i ? true : false);
        }
        if(i == 'INIT'){
            $scope.transStatus3 = ($scope.transStatus3 == i ? '' : i);
            $scope.checkTransStatus3 = ($scope.transStatus3 == i ? true : false);
        }
        if(i == 'SENDORDER'){
            $scope.transStatus4 = ($scope.transStatus4 == i ? '' : i);
            $scope.checkTransStatus4 = ($scope.transStatus4 == i ? true : false);
        }
    }

})